package com.lujianfei.recyclerview.behavior;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.view.ViewCompat;

public class ScrollHideBottomBehavior extends CoordinatorLayout.Behavior<View> {

    private static final String TAG = "ScrollHideBottom==";

    private ObjectAnimator outAnimator,inAnimator;

    public ScrollHideBottomBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View directTargetChild, @NonNull View target, int axes, int type) {
        //ViewCompat是一个兼容类,在android5.0之前的API为了实现新的效果
        //避免出错使用ViewCompat.xxxx方法可以解决出现低版本错误的问题
        return (axes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0;//判断是否竖直滚动
    }

    @Override
    public void onNestedPreScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View target, int dx, int dy, @NonNull int[] consumed, int type) {
        super.onNestedPreScroll(coordinatorLayout,child,target,dx,dy,consumed,type);
        Log.d(TAG,"onNestedPreScroll child = " + child + " target = " + target);
        // child : AppCompatTextView
        // target : RecyclerView
        if (dy > 0) { // 上滑隐藏

            hide(child);

        } else if (dy < 0) { // 下滑显示

            show(child);
        }
    }

    private void hide(View buttomViewScrollHide) {
        if (null == outAnimator) {
            outAnimator = ObjectAnimator.ofFloat(buttomViewScrollHide, "translationY", 0, buttomViewScrollHide.getHeight());
            outAnimator.setDuration(200);
        }

        if (!outAnimator.isRunning() && buttomViewScrollHide.getTranslationY() <= 0) {
            outAnimator.start();
        }
    }

    private void show(View buttomViewScrollHide) {
        if (null == inAnimator) {
            inAnimator = ObjectAnimator.ofFloat(buttomViewScrollHide, "translationY", buttomViewScrollHide.getHeight(),0);
            inAnimator.setDuration(200);
        }

        if (!inAnimator.isRunning() && buttomViewScrollHide.getTranslationY() >= buttomViewScrollHide.getHeight()) {
            inAnimator.start();
        }
    }
}
